package com.harmay.center.monitor.service.impl;

import com.harmay.center.monitor.entity.MetricBaseMapping;
import com.harmay.center.monitor.entity.MetricHistory;
import com.harmay.center.monitor.enums.SendTypeEnum;
import com.harmay.center.monitor.mapper.MetricHistoryMapper;
import com.harmay.center.monitor.service.MetricSendTypeService;
import com.harmay.center.monitor.utils.DingBotUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Zuper
 * @version 1.0
 * @date 2023/2/8 11:42
 */
@Service
@Slf4j
public class DingTypeMonitorServiceImpl implements MetricSendTypeService {
    @Autowired
    private MetricHistoryMapper metricHistoryMapper;

    @Override
    public String typeChoose() {
        return SendTypeEnum.DINGDING.getType();
    }

    @Override
    public void handle(List<MetricBaseMapping> metricBaseMappings, String message, List<String> users) throws IOException {
        List<String> feedbackUsers = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(users)){
            feedbackUsers = users;
        }else{
            feedbackUsers = metricBaseMappings.stream().map(MetricBaseMapping::getMobile).collect(Collectors.toList());
        }
        String token = metricBaseMappings.get(0).getDingdingToken();
        String subjectName = metricBaseMappings.get(0).getSubjectName();
        DingBotUtils.sendMessage(message, token, feedbackUsers);
        metricHistoryMapper.insert(MetricHistory.create(subjectName, message));
    }
}
